package actions;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.EventModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DBModel;

@WebServlet
public class EventSignUpAction extends Action{
	private int eventId=-1;

	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response){
		try{
			String username = request.getParameter("username");
			eventId = Integer.parseInt(request.getParameter("eventId"));
			DBModel db=new DBModel();
		
			EventModel event=db.getEvent(eventId);
			if(event.deadlineHasPassed()){
				request.setAttribute("error", "Deadline has passed!");
				return new ActionForward(mapping.findForward("deadlinePassed").getPath()+"?id="+eventId, false);
			}
			else if(event.getStatus().equals("full")){
				request.setAttribute("error", "The event is full");
				return new ActionForward(mapping.findForward("success").getPath()+"?id="+eventId, false);
			}
			else{
				int userId=db.getUserId(username);
				if(userId!=-1)
				{
					int userState=db.getUserStatus(eventId, userId);
					if(userState>0)
					{
						//You are already signed up
						//response.sendRedirect("Event?id="+eventId);
						db.close();
						return new ActionForward(mapping.findForward("success").getPath()+"?id="+eventId, false);
					}
					else
					{	
						db.signUpForEvent(userId, eventId);		
						db.close();
						return new ActionForward(mapping.findForward("success").getPath()+"?id="+eventId, false);
					}
				}
			}
			
		}catch (Exception e){
			e.printStackTrace();
			request.setAttribute("error", e.toString());
			return mapping.findForward("fail");
		}	
		
		return mapping.findForward("fail");

	}
}
